import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import apiBaseConfig from '@/constants/config.js'

// axios请求超时重新请求次数和时间间隙
//重新请求次数
axios.defaults.retry = 1;
//间隙
axios.defaults.retryDelay = 1000;

// create an axios instance
const service = axios.create({
	baseURL: `${apiBaseConfig.domain}${apiBaseConfig.prefix}`,
	timeout: 6000,  //6s超时 重新请求一次
	crossDomain: true,
	sslVerify:false,
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded'
	}
})

// request拦截器,在请求之前做一些处理
service.interceptors.request.use(
    config => {
		if(!config.data){
			config.data = {};
		}
		if(config.headers['Content-Type'].indexOf('application/x-www-form-urlencoded') > -1){
			// 参数格式转换
			config.data = qs.stringify(config.data);
		}
        return config;
    },
    error => {
        return Promise.reject(error);
    }
); 

//配置成功后的拦截器
service.interceptors.response.use(function succesReslut(res){
	console.log(9999)
}, function axiosRetryInterceptor(err) {
    var config = err.config;
    // If config does not exist or the retry option is not set, reject
    if(!config || !config.retry) return Promise.reject(err);
    
    // Set the variable for keeping track of the retry count
    config.__retryCount = config.__retryCount || 0;
    
    // Check if we've maxed out the total number of retries
    if(config.__retryCount >= config.retry) {
        // Reject with the error
        return Promise.reject(err);
    }
    
    // Increase the retry count
    config.__retryCount += 1;
    
    // Create new promise to handle exponential backoff
    var backoff = new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, config.retryDelay || 1);
    });
    
    // Return the promise in which recalls axios to retry the request
    return backoff.then(function() {
        return service(config);
    });
});

// 在main.js中放入这段自定义适配器的代码，就可以实现uniapp的app和小程序开发中能使用axios进行跨域网络请求，并支持携带cookie
axios.defaults.adapter = function(config) { 
    return new Promise((resolve, reject) => {
        var settle = require('axios/lib/core/settle');
        var buildURL = require('axios/lib/helpers/buildURL');
        uni.request({
            method: config.method.toUpperCase(),
            url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
            header: config.headers,
            data: config.data,
            dataType: config.dataType,
            responseType: config.responseType,
            sslVerify: config.sslVerify,
            complete: function complete(response) {
                console.log("执行完成：",response)
                response = {
                    data: response.data,
                    status: response.statusCode,
                    errMsg: response.errMsg,
                    header: response.header,
                    config: config
                };

                settle(resolve, reject, response);
            }
        })
    })
}

export default service